package com.situ.gym.service.impl;

import com.alibaba.excel.EasyExcel;
import com.situ.gym.listener.CoachCourseExcelListener;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.situ.gym.mapper.CoachCourseMapper;
import com.situ.gym.pojo.Course;
import com.situ.gym.pojo.query.CoachCourseQuery;
import com.situ.gym.pojo.vo.CoachCourseVO;
import com.situ.gym.pojo.vo.CourseExcelVO;
import com.situ.gym.service.ICoachCourseService;
import com.situ.gym.util.ExcelUtil;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 教练课程管理服务实现类
 *
 * @author ${author}
 * @since 2025-01-27
 */
@Service
public class CoachCourseServiceImpl extends ServiceImpl<CoachCourseMapper, Course> implements ICoachCourseService {

    @Autowired
    private CoachCourseMapper coachCourseMapper;

    @Override
    public IPage<CoachCourseVO> list(CoachCourseQuery coachCourseQuery) {
        IPage<CoachCourseVO> page = new Page<>(coachCourseQuery.getPage(), coachCourseQuery.getLimit());
        return coachCourseMapper.list(page, coachCourseQuery);
    }

    @Override
    public void deleteAll(Long[] ids) {
        coachCourseMapper.deleteAll(ids);
    }

    @Override
    public void exportExcel(HttpServletResponse response, Long coachId) {
        // 查询当前教练的所有课程
        List<Course> list = this.lambdaQuery()
                .eq(Course::getCoachId, coachId)
                .list();
        
        // 转换为Excel VO对象
        ArrayList<CourseExcelVO> courseExcelVOList = new ArrayList<>();
        for (Course course : list) {
            CourseExcelVO courseExcelVO = new CourseExcelVO();
            BeanUtils.copyProperties(course, courseExcelVO);
            courseExcelVOList.add(courseExcelVO);
        }
        
        // 导出Excel
        ExcelUtil.exportExcel(response, courseExcelVOList, CourseExcelVO.class, "coach_course");
    }

    @Override
    public void importExcel(MultipartFile file, Long coachId) {
        try {
            // 创建自定义监听器，自动设置教练ID
            CoachCourseExcelListener listener = new CoachCourseExcelListener(coachCourseMapper, coachId);
            EasyExcel.read(file.getInputStream(), CourseExcelVO.class, listener).sheet().doRead();
        } catch (IOException e) {
            throw new RuntimeException("导入Excel失败", e);
        }
    }

}
